package com.zst.http.forward.remote.httppacket;

import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;

import java.nio.charset.StandardCharsets;

public class HttpRequestBodyHelper {
    public static void handleRequestBody(MultiplexHttpClient.Request forwardReq, FullHttpRequest sourceReq) {
        String contentType = sourceReq.headers().get(HttpHeaderNames.CONTENT_TYPE);
        if (contentType == null) {
            return;
        }

        String contentEncode = "utf-8";
        if (contentType.contains(";")) {
            String[] parts = contentType.split(";");
            contentType = parts[0].trim();

            for (int i = 1; i < parts.length; i++) {
                if (parts[i].trim().startsWith("charset=")) {
                    contentEncode = parts[i].trim().substring("charset=".length());
                }
            }
        }

        switch (contentType) {
            case "application/json":
                forwardReq.jsonBody(extractJsonBody(sourceReq, contentEncode));
                break;
            default:
                // 实际上multipart/form-data类型的数据时行不通的，因为还有boundary这个值的存在，直接复制源header的话，可能会跟实际
                // 由http工具生成的boundary不一样
                // 不对，好像也没啥问题，整个body都被我copy过去了，boundary是一样的才对
                forwardReq.byteStreamBody(extractByteStreamBody(sourceReq));
        }
    }


    private static String extractJsonBody(FullHttpRequest sourceReq, String contentEncode) {
        if (sourceReq.content().readableBytes() <= 0) {
            return "{}";
        }

        try {
            byte[] bytes = new byte[sourceReq.content().readableBytes()];
            sourceReq.content().readBytes(bytes);

            if (contentEncode != null) {
                return new String(bytes, contentEncode);
            } else {
                return new String(bytes, StandardCharsets.UTF_8);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static byte[] extractByteStreamBody(FullHttpRequest sourceReq) {
        if (sourceReq.content().readableBytes() <= 0) {
            return new byte[0];
        }

        try {
            byte[] bytes = new byte[sourceReq.content().readableBytes()];
            sourceReq.content().readBytes(bytes);

            return bytes;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
